<template>
  <lay-layer
    v-model="visible"
    :title="mode === 'add' ? '新增商品' : '编辑商品'"
    :area="['90%', '95%']"
    :maxmin="true"
    :resize="true"
    @close="handleClose"
  >
    <div class="product-dialog">
      <div class="dialog-container">
        <!-- 左侧表单区域 -->
        <div class="form-section">
          <lay-form :model="formData" ref="formRef" required>
            <!-- 基本信息 -->
            <div class="section-card">
              <div class="section-header">
                <h3>基本信息</h3>
              </div>
              <div class="section-content">
                <!-- 商品名称 -->
                <div class="form-group">
                  <lay-form-item label="商品名称" prop="name" required>
                    <lay-input 
                      v-model="formData.name" 
                      placeholder="请输入商品名称" 
                      size="lg"
                    />
                  </lay-form-item>
                </div>

                <!-- 副标题 -->
                <div class="form-group">
                  <lay-form-item label="副标题/卖点">
                    <lay-input 
                      v-model="formData.subtitle" 
                      placeholder="请输入商品副标题或卖点" 
                      size="lg"
                    />
                  </lay-form-item>
                </div>

                <!-- SPU编码 -->
                <div class="form-group">
                  <lay-form-item label="SPU编码">
                    <div class="spu-code-group">
                      <lay-input 
                        v-model="formData.spuCode" 
                        placeholder="SPU编码（自动生成）" 
                        size="lg"
                        readonly
                      />
                      <lay-button 
                        type="primary" 
                        size="lg"
                        @click="generateSpuCode"
                        :loading="generatingSpuCode"
                        class="generate-btn"
                      >
                        {{ generatingSpuCode ? '生成中...' : '重新生成' }}
                      </lay-button>
                    </div>
                  </lay-form-item>
                </div>

                <!-- 分类和品牌 -->
                <div class="form-group">
                  <lay-row :space="20">
                    <lay-col :md="12">
                      <lay-form-item label="商品分类" prop="categoryId" required>
                        <lay-select 
                          v-model="formData.categoryId" 
                          placeholder="请选择商品分类"
                          size="lg"
                        >
                          <lay-select-option 
                            v-for="category in flatCategories" 
                            :key="category.id" 
                            :value="category.id"
                          >
                            {{ category.displayName || category.name }}
                          </lay-select-option>
                        </lay-select>
                      </lay-form-item>
                    </lay-col>
                    <lay-col :md="12">
                      <lay-form-item label="商品品牌" prop="brandId" required>
                        <lay-select 
                          v-model="formData.brandId" 
                          placeholder="请选择商品品牌"
                          size="lg"
                        >
                          <lay-select-option 
                            v-for="brand in brands" 
                            :key="brand.id" 
                            :value="brand.id"
                          >
                            {{ brand.name }}
                          </lay-select-option>
                        </lay-select>
                      </lay-form-item>
                    </lay-col>
                  </lay-row>
                </div>

                <!-- 价格信息 -->
                <div class="form-group">
                  <div class="group-title">价格信息</div>
                  <lay-row :space="20">
                    <lay-col :md="8">
                      <lay-form-item label="销售价格" prop="price" required>
                        <lay-input-number 
                          v-model="formData.price" 
                          :min="0" 
                          :step="0.01"
                          placeholder="0.00"
                          size="lg"
                        />
                      </lay-form-item>
                    </lay-col>
                    <lay-col :md="8">
                      <lay-form-item label="市场价">
                        <lay-input-number 
                          v-model="formData.marketPrice" 
                          :min="0" 
                          :step="0.01"
                          placeholder="0.00"
                          size="lg"
                        />
                      </lay-form-item>
                    </lay-col>
                    <lay-col :md="8">
                      <lay-form-item label="成本价格">
                        <lay-input-number 
                          v-model="formData.costPrice" 
                          :min="0" 
                          :step="0.01"
                          placeholder="0.00"
                          size="lg"
                        />
                      </lay-form-item>
                    </lay-col>
                  </lay-row>
                </div>

                <!-- 关键词 -->
                <div class="form-group">
                  <lay-form-item label="关键词">
                    <lay-input 
                      v-model="formData.keywords" 
                      placeholder="请输入商品关键词，用逗号分隔" 
                      size="lg"
                    />
                  </lay-form-item>
                </div>

                <!-- 库存和状态 -->
                <div class="form-group">
                  <div class="group-title">库存状态</div>
                  <lay-row :space="20">
                    <lay-col :md="6">
                      <lay-form-item label="库存数量" prop="stockQuantity" required>
                        <lay-input-number 
                          v-model="formData.stockQuantity" 
                          :min="0"
                          placeholder="0"
                          size="lg"
                        />
                      </lay-form-item>
                    </lay-col>
                    <lay-col :md="6">
                      <lay-form-item label="销量">
                        <lay-input-number 
                          v-model="formData.saleCount" 
                          :min="0"
                          placeholder="0"
                          size="lg"
                          :disabled="mode === 'add'"
                        />
                      </lay-form-item>
                    </lay-col>
                    <lay-col :md="6">
                      <lay-form-item label="商品状态">
                        <lay-select v-model="formData.status" size="lg">
                          <lay-select-option :value="1">上架</lay-select-option>
                          <lay-select-option :value="0">下架</lay-select-option>
                          <lay-select-option :value="2">草稿</lay-select-option>
                        </lay-select>
                      </lay-form-item>
                    </lay-col>
                    <lay-col :md="6">
                      <lay-form-item label="排序权重">
                        <lay-input-number 
                          v-model="formData.sortOrder" 
                          :min="0"
                          placeholder="数值越大越靠前"
                          size="lg"
                        />
                      </lay-form-item>
                    </lay-col>
                  </lay-row>
                </div>

                <!-- 商品标签 -->
                <div class="form-group">
                  <lay-form-item label="商品标签">
                    <lay-checkbox-group v-model="selectedTags" class="tag-group">
                      <lay-checkbox value="推荐">推荐</lay-checkbox>
                      <lay-checkbox value="热销">热销</lay-checkbox>
                      <lay-checkbox value="新品">新品</lay-checkbox>
                    </lay-checkbox-group>
                  </lay-form-item>
                </div>

                <!-- 商品描述 -->
                <div class="form-group">
                  <lay-form-item label="商品描述">
                    <lay-textarea 
                      v-model="formData.description" 
                      :rows="4"
                      placeholder="请输入商品描述"
                    />
                  </lay-form-item>
                </div>

                <!-- 商品视频 -->
                <div class="form-group">
                  <lay-form-item label="商品视频">
                    <div class="video-upload-container">
                      <div v-if="formData.videoUrl" class="video-preview">
                        <video 
                          :src="formData.videoUrl" 
                          controls 
                          style="width: 200px; height: 120px; object-fit: cover; border-radius: 4px;"
                        ></video>
                        <div class="video-actions">
                          <lay-button size="xs" type="primary" @click="selectVideo">更换视频</lay-button>
                          <lay-button size="xs" type="danger" @click="removeVideo">删除视频</lay-button>
                        </div>
                      </div>
                      <div v-else class="video-upload-area" @click="selectVideo">
                        <lay-icon type="layui-icon-upload" size="24"></lay-icon>
                        <p>点击上传视频</p>
                        <p class="upload-tip">支持 MP4、AVI、MOV 格式，大小不超过 100MB</p>
                      </div>
                      <input 
                        ref="videoInput" 
                        type="file" 
                        accept="video/*" 
                        style="display: none" 
                        @change="handleVideoUpload"
                      />
                    </div>
                  </lay-form-item>
                </div>

                <!-- 服务信息 -->
                <div class="form-group">
                  <lay-form-item label="服务信息">
                    <lay-textarea 
                      v-model="formData.serviceInfo" 
                      :rows="3"
                      placeholder="请输入服务信息，如售后保障、退换货政策等"
                    />
                  </lay-form-item>
                </div>

                <!-- 配送信息 -->
                <div class="form-group">
                  <lay-form-item label="配送信息">
                    <lay-textarea 
                      v-model="formData.shippingInfo" 
                      :rows="3"
                      placeholder="请输入配送信息，如配送范围、配送时间等"
                    />
                  </lay-form-item>
                </div>
              </div>
            </div>

            <!-- 规格参数 -->
            <div class="section-card">
              <div class="section-header">
                <h3>规格参数</h3>
                <lay-button size="sm" @click="addSpecification">
                  <lay-icon type="layui-icon-add-1"></lay-icon>
                  添加规格
                </lay-button>
              </div>
              <div class="section-content">
                <div class="specifications-list">
                  <div 
                    v-for="(spec, index) in specifications" 
                    :key="index"
                    class="spec-item"
                  >
                    <lay-input 
                      v-model="spec.name" 
                      placeholder="规格名称"
                      class="spec-name"
                    />
                    <lay-input 
                      v-model="spec.value" 
                      placeholder="规格值"
                      class="spec-value"
                    />
                    <lay-button 
                      size="sm" 
                      type="danger" 
                      @click="removeSpecification(index)"
                    >
                      删除
                    </lay-button>
                  </div>
                </div>

                <lay-row :space="16" style="margin-top: 16px;">
                  <lay-col :md="12">
                    <lay-form-item label="商品重量(kg)">
                      <lay-input-number 
                        v-model="formData.weight" 
                        :min="0"
                        :step="0.001"
                        placeholder="0.000"
                      />
                    </lay-form-item>
                  </lay-col>
                  <lay-col :md="12">
                    <lay-form-item label="单位">
                      <lay-input 
                        v-model="formData.unit" 
                        placeholder="件"
                      />
                    </lay-form-item>
                  </lay-col>
                </lay-row>

                <div class="group-title" style="margin-top: 16px;">商品尺寸 (mm)</div>
                <lay-row :space="16">
                  <lay-col :md="8">
                    <lay-form-item label="长度">
                      <lay-input-number 
                        v-model="formData.volumeLength" 
                        :min="0"
                        placeholder="0"
                      />
                    </lay-form-item>
                  </lay-col>
                  <lay-col :md="8">
                    <lay-form-item label="宽度">
                      <lay-input-number 
                        v-model="formData.volumeWidth" 
                        :min="0"
                        placeholder="0"
                      />
                    </lay-form-item>
                  </lay-col>
                  <lay-col :md="8">
                    <lay-form-item label="高度">
                      <lay-input-number 
                        v-model="formData.volumeHeight" 
                        :min="0"
                        placeholder="0"
                      />
                    </lay-form-item>
                  </lay-col>
                </lay-row>
              </div>
            </div>
          </lay-form>
        </div>

        <!-- 右侧图片管理区域 -->
        <div class="image-section">
          <div class="section-card">
            <div class="section-header">
              <h3>商品图片</h3>
              <span class="image-count">{{ formData.images.length }}/10</span>
            </div>
            <div class="section-content">
              <div class="image-upload-area">
                <div class="image-grid">
                  <div 
                    v-for="(image, index) in formData.images" 
                    :key="index"
                    class="image-item"
                    :class="{ 'is-main': index === 0 }"
                  >
                    <img :src="image" :alt="`商品图片${index + 1}`" />
                    <div class="image-overlay">
                      <div class="image-actions">
                        <lay-button 
                          size="xs" 
                          @click="moveImage(index, -1)" 
                          :disabled="index === 0"
                          title="上移"
                        >
                          <lay-icon type="layui-icon-up"></lay-icon>
                        </lay-button>
                        <lay-button 
                          size="xs" 
                          @click="moveImage(index, 1)" 
                          :disabled="index === formData.images.length - 1"
                          title="下移"
                        >
                          <lay-icon type="layui-icon-down"></lay-icon>
                        </lay-button>
                        <lay-button 
                          size="xs" 
                          type="danger" 
                          @click="removeImage(index)"
                          title="删除"
                        >
                          <lay-icon type="layui-icon-delete"></lay-icon>
                        </lay-button>
                      </div>
                    </div>
                    <div v-if="index === 0" class="main-badge">主图</div>
                  </div>
                  
                  <div 
                    v-if="formData.images.length < 10"
                    class="upload-item" 
                    @click="handleImageUpload"
                  >
                    <lay-icon type="layui-icon-add-1" size="32"></lay-icon>
                    <div class="upload-text">上传图片</div>
                  </div>
                </div>

                <div class="upload-tips">
                  <h4>上传要求：</h4>
                  <ul>
                    <li>建议尺寸：800x800像素</li>
                    <li>支持格式：JPG、PNG、WEBP</li>
                    <li>文件大小：不超过2MB</li>
                    <li>最多上传10张图片</li>
                    <li>第一张图片将作为主图显示</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作区域 -->
      <div class="dialog-footer">
        <div class="footer-actions">
          <lay-button @click="handleClose" size="lg">取消</lay-button>
          <lay-button 
            type="primary" 
            @click="handleSubmit" 
            :loading="loading"
            size="lg"
          >
            {{ mode === 'add' ? '创建商品' : '更新商品' }}
          </lay-button>
        </div>
      </div>
    </div>

    <!-- 隐藏的文件上传 -->
    <input 
      ref="fileInput"
      type="file"
      accept="image/*"
      multiple
      style="display: none"
      @change="handleFileChange"
    />
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { layer } from '@layui/layui-vue'
import { productApi } from '../../../../api/module/product'
import { CategoryApi } from '../../../../api/module/category'
import { brandApi } from '../../../../api/module/brand'
import { UploadApi } from '../../../../api/module/upload'

interface Props {
  visible: boolean
  productData?: any
  mode: 'add' | 'edit'
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const generatingSpuCode = ref(false)
const formRef = ref()
const fileInput = ref()
const videoInput = ref()

// 表单数据
const formData = reactive({
  name: '',
  subtitle: '',
  spuCode: '',
  description: '',
  categoryId: null as number | null,
  brandId: null as number | null,
  price: 0,
  marketPrice: 0,
  costPrice: 0,
  stockQuantity: 0,
  saleCount: 0,
  status: 1,
  images: [] as string[],
  videoUrl: '',
  specifications: {},
  weight: 0,
  volumeLength: 0,
  volumeWidth: 0,
  volumeHeight: 0,
  keywords: '',
  serviceInfo: '',
  shippingInfo: '',
  tags: [] as string[],
  sortOrder: 0,
  isRecommend: 0,
  isHot: 0,
  isNew: 0,
  unit: '件'
})

// 规格数据
const specifications = ref<Array<{ name: string; value: string }>>([])

// 选中的标签
const selectedTags = ref<string[]>([])

// 分类和品牌数据
const categories = ref<any[]>([])
const brands = ref<any[]>([])
const flatCategories = ref<any[]>([])

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听标签变化
watch(selectedTags, (newTags) => {
  formData.isRecommend = newTags.includes('推荐') ? 1 : 0
  formData.isHot = newTags.includes('热销') ? 1 : 0
  formData.isNew = newTags.includes('新品') ? 1 : 0
  formData.tags = newTags
}, { deep: true })

// 监听规格变化
watch(specifications, (newSpecs) => {
  const specs: Record<string, any> = {}
  newSpecs.forEach(spec => {
    if (spec.name && spec.value) {
      specs[spec.name] = spec.value
    }
  })
  formData.specifications = specs
}, { deep: true })

// 监听弹窗显示
watch(() => props.visible, async (newVal) => {
  if (newVal) {
    initForm()
    await getCategories()
    await getBrands()
    
    // 如果是新增模式，自动生成SPU编码
    if (props.mode === 'add') {
      // 延迟一下确保分类和品牌数据已加载
      setTimeout(() => {
        generateSpuCode()
      }, 100)
    }
  }
})

// 监听分类和品牌变化，自动重新生成SPU编码
watch([() => formData.categoryId, () => formData.brandId], () => {
  if (props.mode === 'add' && (formData.categoryId || formData.brandId)) {
    generateSpuCode()
  }
})

// 初始化表单
const initForm = () => {
  if (props.mode === 'edit' && props.productData) {
    // 安全地映射数据，确保类型正确
    const data = props.productData
    Object.assign(formData, {
      name: data.name || '',
      subtitle: data.subtitle || '',
      spuCode: data.spuCode || '',
      description: data.description || '',
      categoryId: data.categoryId || (data.category?.id) || null,
      brandId: data.brandId || (data.brand?.id) || null,
      price: Number(data.price) || 0,
      marketPrice: Number(data.marketPrice) || 0,
      costPrice: Number(data.costPrice) || 0,
      stockQuantity: Number(data.stockQuantity) || 0,
      saleCount: Number(data.saleCount) || 0,
      status: Number(data.status) || 1,
      images: Array.isArray(data.images) ? data.images : [],
      videoUrl: data.videoUrl || '',
      specifications: data.specifications || {},
      weight: Number(data.weight) || 0,
      volumeLength: Number(data.volumeLength) || 0,
      volumeWidth: Number(data.volumeWidth) || 0,
      volumeHeight: Number(data.volumeHeight) || 0,
      keywords: data.keywords || '',
      serviceInfo: data.serviceInfo || '',
      shippingInfo: data.shippingInfo || '',
      tags: [],
      sortOrder: Number(data.sortOrder) || 0,
      isRecommend: Number(data.isRecommend) || 0,
      isHot: Number(data.isHot) || 0,
      isNew: Number(data.isNew) || 0,
      unit: data.unit || '件'
    })
    
    // 处理标签
    const tags = []
    if (formData.isRecommend) tags.push('推荐')
    if (formData.isHot) tags.push('热销')
    if (formData.isNew) tags.push('新品')
    selectedTags.value = tags

    // 处理规格
    if (formData.specifications && typeof formData.specifications === 'object') {
      specifications.value = Object.entries(formData.specifications).map(([name, value]) => ({
        name,
        value: String(value)
      }))
    }
  } else {
    // 重置表单
    Object.assign(formData, {
      name: '',
      subtitle: '',
      spuCode: '',
      description: '',
      categoryId: null,
      brandId: null,
      price: 0,
      marketPrice: 0,
      costPrice: 0,
      stockQuantity: 0,
      saleCount: 0,
      status: 1,
      images: [],
      videoUrl: '',
      specifications: {},
      weight: 0,
      volumeLength: 0,
      volumeWidth: 0,
      volumeHeight: 0,
      keywords: '',
      serviceInfo: '',
      shippingInfo: '',
      tags: [],
      sortOrder: 0,
      isRecommend: 0,
      isHot: 0,
      isNew: 0,
      unit: '件'
    })
    selectedTags.value = []
    specifications.value = []
  }
}

// 扁平化分类树
const flattenCategories = (categories: any[], level = 0): any[] => {
  const result: any[] = []
  categories.forEach(category => {
    // 添加当前分类，使用缩进表示层级
    const prefix = '　'.repeat(level) // 使用全角空格缩进
    result.push({
      ...category,
      displayName: `${prefix}${category.name}`
    })
    
    // 递归处理子分类
    if (category.children && category.children.length > 0) {
      result.push(...flattenCategories(category.children, level + 1))
    }
  })
  return result
}

// 获取分类列表
const getCategories = async () => {
  try {
    const response = await CategoryApi.getAllVisibleCategories()
    // 根据实际响应格式处理数据
    if (response.data && response.data.code === 200) {
      categories.value = response.data.data
      flatCategories.value = flattenCategories(response.data.data)
    } else if (response.data && Array.isArray(response.data)) {
      categories.value = response.data
      flatCategories.value = flattenCategories(response.data)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取品牌列表
const getBrands = async () => {
  try {
    const response = await brandApi.getAllVisibleBrands()
    if (response.code === 200) {
      brands.value = response.data
    }
  } catch (error) {
    console.error('获取品牌列表失败:', error)
  }
}

// 添加规格
const addSpecification = () => {
  specifications.value.push({ name: '', value: '' })
}

// 删除规格
const removeSpecification = (index: number) => {
  specifications.value.splice(index, 1)
}

// 生成SPU编码
const generateSpuCode = async () => {
  try {
    generatingSpuCode.value = true
    
    // 生成SPU编码规则：分类前缀 + 品牌前缀 + 时间戳 + 随机数
    const categoryPrefix = getCategoryPrefix()
    const brandPrefix = getBrandPrefix()
    const timestamp = Date.now().toString().slice(-6) // 取时间戳后6位
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0') // 3位随机数
    
    const spuCode = `${categoryPrefix}${brandPrefix}${timestamp}${random}`
    formData.spuCode = spuCode
    
    layer.msg('SPU编码生成成功', { icon: 1 })
  } catch (error) {
    console.error('生成SPU编码失败:', error)
    layer.msg('生成SPU编码失败', { icon: 2 })
  } finally {
    generatingSpuCode.value = false
  }
}

// 获取分类前缀
const getCategoryPrefix = () => {
  if (!formData.categoryId) return 'CAT'
  
  const category = flatCategories.value.find(cat => cat.id === formData.categoryId)
  if (category && category.name) {
    // 取分类名称的首字母或前两个字符
    const name = category.name.replace(/[^\u4e00-\u9fa5a-zA-Z]/g, '') // 只保留中英文
    if (name.length >= 2) {
      return name.substring(0, 2).toUpperCase()
    } else if (name.length === 1) {
      return name.toUpperCase() + 'C'
    }
  }
  return 'CAT'
}

// 获取品牌前缀
const getBrandPrefix = () => {
  if (!formData.brandId) return 'BR'
  
  const brand = brands.value.find(b => b.id === formData.brandId)
  if (brand && brand.name) {
    // 取品牌名称的首字母或前两个字符
    const name = brand.name.replace(/[^\u4e00-\u9fa5a-zA-Z]/g, '') // 只保留中英文
    if (name.length >= 2) {
      return name.substring(0, 2).toUpperCase()
    } else if (name.length === 1) {
      return name.toUpperCase() + 'B'
    }
  }
  return 'BR'
}

// 图片上传
const handleImageUpload = () => {
  if (formData.images.length >= 10) {
    layer.msg('最多只能上传10张图片', { icon: 3 })
    return
  }
  fileInput.value?.click()
}

// 文件选择
const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files
  if (!files || files.length === 0) return

  const remainingSlots = 10 - formData.images.length
  const filesToUpload = Array.from(files).slice(0, remainingSlots)

  for (const file of filesToUpload) {
    // 验证文件
    if (!file.type.startsWith('image/')) {
      layer.msg('只能上传图片文件', { icon: 3 })
      continue
    }
    if (file.size > 2 * 1024 * 1024) {
      layer.msg('图片大小不能超过2MB', { icon: 3 })
      continue
    }

    try {
      const response = await UploadApi.uploadImage(file)
      // HTTP拦截器在成功时返回 { code: 200, message: '...', data: {...}, timestamp: '...' }
      if (response.code === 200 && response.data?.url) {
        formData.images.push(response.data.url)
        layer.msg('图片上传成功', { icon: 1 })
      } else {
        layer.msg(response.message || '图片上传失败', { icon: 2 })
      }
    } catch (error) {
      console.error('图片上传失败:', error)
      layer.msg('图片上传失败', { icon: 2 })
    }
  }

  // 清空文件输入
  target.value = ''
}

// 移动图片
const moveImage = (index: number, direction: number) => {
  const newIndex = index + direction
  if (newIndex < 0 || newIndex >= formData.images.length) return

  const images = [...formData.images]
  const temp = images[index]
  images[index] = images[newIndex]
  images[newIndex] = temp
  formData.images = images
}

// 删除图片
const removeImage = (index: number) => {
  formData.images.splice(index, 1)
}

// 选择视频文件
const selectVideo = () => {
  videoInput.value?.click()
}

// 处理视频上传
const handleVideoUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('video/')) {
    layer.msg('只能上传视频文件', { icon: 3 })
    return
  }

  // 验证文件大小 (100MB)
  if (file.size > 100 * 1024 * 1024) {
    layer.msg('视频文件大小不能超过100MB', { icon: 3 })
    return
  }

  try {
    layer.msg('视频上传中...', { icon: 16, time: 0 })
    const response = await UploadApi.uploadVideo(file)
    
    if (response.code === 200 && response.data?.url) {
      formData.videoUrl = response.data.url
      layer.closeAll()
      layer.msg('视频上传成功', { icon: 1 })
    } else {
      layer.closeAll()
      layer.msg(response.message || '视频上传失败', { icon: 2 })
    }
  } catch (error) {
    console.error('视频上传失败:', error)
    layer.closeAll()
    layer.msg('视频上传失败', { icon: 2 })
  }

  // 清空文件输入
  target.value = ''
}

// 删除视频
const removeVideo = () => {
  formData.videoUrl = ''
  layer.msg('视频已删除', { icon: 1 })
}

// 表单验证规则
const validateForm = () => {
  const errors = []
  
  if (!formData.name.trim()) {
    errors.push('商品名称不能为空')
  }
  
  if (!formData.categoryId) {
    errors.push('请选择商品分类')
  }
  
  if (!formData.brandId) {
    errors.push('请选择商品品牌')
  }
  
  if (formData.price <= 0) {
    errors.push('销售价格必须大于0')
  }
  
  if (formData.stockQuantity < 0) {
    errors.push('库存数量不能小于0')
  }
  
  if (formData.images.length === 0) {
    errors.push('请至少上传一张商品图片')
  }
  
  return errors
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    const errors = validateForm()
    if (errors.length > 0) {
      layer.msg(errors[0], { icon: 3 })
      return
    }

    loading.value = true

    // 准备提交数据
    const submitData = {
      ...formData,
      mainImage: formData.images[0] || '', // 第一张图片作为主图
      keywords: formData.tags.join(','), // 标签转换为关键词
    }
    
    // 删除前端特有的字段
    delete submitData.tags
    delete submitData.dimensions
    
    if (props.mode === 'add') {
      const response = await productApi.createProduct(submitData)
      if (response.code === 200) {
        layer.msg('创建成功', { icon: 1 })
        emit('success')
        handleClose()
      } else {
        layer.msg(response.message || '创建失败', { icon: 2 })
      }
    } else {
      const response = await productApi.updateProduct(props.productData.id, submitData)
      if (response.code === 200) {
        layer.msg('更新成功', { icon: 1 })
        emit('success')
        handleClose()
      } else {
        layer.msg(response.message || '更新失败', { icon: 2 })
      }
    }
  } catch (error: any) {
    console.error('提交失败:', error)
    const errorMsg = error.response?.data?.message || error.message || '提交失败'
    layer.msg(errorMsg, { icon: 2 })
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.product-dialog {
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.dialog-container {
  flex: 1;
  display: flex;
  gap: 20px;
  padding: 20px;
  overflow: hidden;
}

.form-section {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
}

.image-section {
  width: 400px;
  overflow-y: auto;
}

.section-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
  border-radius: 8px 8px 0 0;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.section-content {
  padding: 20px;
}

/* 表单分组样式 */
.form-group {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.form-group:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.group-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-left: 4px;
  border-left: 3px solid #1890ff;
  background: #f8f9fa;
  padding: 8px 12px;
  border-radius: 4px;
}

.tag-group {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.specifications-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.spec-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.spec-name {
  width: 150px;
}

.spec-value {
  flex: 1;
}

.image-upload-area {
  width: 100%;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.image-item {
  position: relative;
  width: 100%;
  height: 160px;
  border: 2px solid #e8e8e8;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.image-item.is-main {
  border-color: #1890ff;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .image-overlay {
  opacity: 1;
}

.image-actions {
  display: flex;
  gap: 8px;
}

.main-badge {
  position: absolute;
  top: 8px;
  left: 8px;
  background: #1890ff;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.upload-item {
  width: 100%;
  height: 160px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #999;
  transition: all 0.3s;
}

.upload-item:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.upload-text {
  margin-top: 8px;
  font-size: 14px;
}

.upload-tips {
  background: #f9f9f9;
  padding: 16px;
  border-radius: 6px;
  border-left: 4px solid #1890ff;
}

.upload-tips h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
}

.upload-tips ul {
  margin: 0;
  padding-left: 16px;
  color: #666;
  font-size: 12px;
  line-height: 1.6;
}

.image-count {
  color: #666;
  font-size: 14px;
}

/* 视频上传样式 */
.video-upload-container {
  width: 100%;
}

.video-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.video-actions {
  display: flex;
  gap: 8px;
}

.video-upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #fafafa;
}

.video-upload-area:hover {
  border-color: #1890ff;
  background-color: #f0f8ff;
}

.video-upload-area p {
  margin: 8px 0 0 0;
  color: #666;
}

.video-upload-area .upload-tip {
  font-size: 12px;
  color: #999;
}

.dialog-footer {
  background: white;
  border-top: 1px solid #e8e8e8;
  padding: 16px 20px;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* SPU编码组合样式 */
.spu-code-group {
  display: flex;
  align-items: center;
  gap: 0;
}

.spu-code-group .layui-input {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  border-right: none;
  flex: 1;
}

.spu-code-group .generate-btn {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  margin-left: 0;
}

/* 滚动条样式 */
.form-section::-webkit-scrollbar,
.image-section::-webkit-scrollbar {
  width: 6px;
}

.form-section::-webkit-scrollbar-track,
.image-section::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.form-section::-webkit-scrollbar-thumb,
.image-section::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.form-section::-webkit-scrollbar-thumb:hover,
.image-section::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>